import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:photo_frame/base/AbsLifecycleState.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/net/model/frame_folder_model.dart';
import 'package:photo_frame/net/model/frame_info_model.dart';
import 'package:photo_frame/provider/app_trans_asset_provider.dart';
import 'package:photo_frame/router/router_context.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:photo_frame/widgets/custom_cupertino_alert_dialog.dart';

class FrameFolderListPage extends StatefulWidget {
  late final FrameInfoModel? frame;

  FrameFolderListPage({super.key}) {
    frame = AppAssetTransProvider.provider().transAssetData(key: "frame");
  }

  @override
  State<FrameFolderListPage> createState() => _FrameFolderListPageState();
}

class _FrameFolderListPageState extends AbsLifecycleState<FrameFolderListPage>
    with SingleTickerProviderStateMixin {
  GlobalKey<RefreshIndicatorState> refreshIndicatorStateKey = GlobalKey();

  @override
  void onResume() {
    super.onResume();
    refreshIndicatorStateKey.currentState?.show();
  }

  FrameFolderModel? selectedFolder;
  List<FrameFolderModel> folderList = [];

  @override
  initState() {
    super.initState();
    fetchFolderList();
  }

  fetchFolderList() async {
    String? frameId = AppAssetTransProvider.provider()
        .transAssetData<FrameInfoModel>(key: "frame")
        ?.frame_id;
    var response = await HttpManager.instance
        .doRequest("/api/getfolder", parameters: {"frame_id": frameId ?? ""});
    if (!response.isSuccess) {
      EasyLoading.showToast(response.msg ?? "");
      return;
    }
    List? folderListData = response.data?["folders"];
    if (folderListData == null) {
      return;
    }
    folderList = folderListData.map((e) {
      FrameFolderModel folder = FrameFolderModel.fromJson(e);
      if (selectedFolder == null) {
        selectedFolder = folder;
      } else {
        if (folder.getName() == selectedFolder?.getName()) {
          selectedFolder = folder;
        }
      }
      return folder;
    }).where((item) {
      var result = item.getName() != "null" && item.getName().isNotEmpty;
      return result;
    }).toList();
    setState(() {});
  }

  void deleteFolder(BuildContext context, FrameFolderModel folder) async {
    if (selectedFolder?.getName() == folder.getName()) {
      selectedFolder = null;
    }
    folderList.remove(folder);
    setState(() {});
    await HttpManager.instance.doRequest("/api/deletedir", parameters: {
      "name": folder.getName(),
      "frame_id": "${widget.frame?.frame_id}"
    });
    refreshIndicatorStateKey.currentState!.show();
  }

  void addFolder(BuildContext context) async {
    showEditFolderDialog(appLocalForContext(context).createNewFrameFolder, "",
        (String folderName) async {
      if (folderName.isEmpty) {
        EasyLoading.showToast(appLocalForContext(context).enterVaildFolderName);
        return;
      }
      for (var folder in folderList) {
        if (folder.getName() == folderName) {
          EasyLoading.showToast(
              appLocalForContext(context).folderNameCantRepeat);
          return;
        }
      }
      EasyLoading.show(
        maskType: EasyLoadingMaskType.black,
      );
      var response = await HttpManager.instance.doRequest("/api/createdir",
          parameters: {
            "name": folderName,
            "frame_id": widget.frame?.frame_id ?? ""
          });
      if (!response.isSuccess) {
        EasyLoading.dismiss();
        EasyLoading.showToast(response.msg ?? "");
      }
      EasyLoading.dismiss();
      refreshIndicatorStateKey.currentState!.show();
    });
  }

  renameFolder(BuildContext context, String oldFolderName) {
    showEditFolderDialog(
        appLocalForContext(context).renameFolderName, oldFolderName,
        (String newFolderName) async {
      if (newFolderName.isEmpty) {
        EasyLoading.showToast(appLocalForContext(context).enterVaildFolderName);
        return;
      }
      if (oldFolderName == newFolderName) {
        return;
      }
      for (var folder in folderList) {
        if (folder.getName() == newFolderName) {
          EasyLoading.showToast(
              appLocalForContext(context).folderNameCantRepeat);
          return;
        }
      }
      EasyLoading.show(
        maskType: EasyLoadingMaskType.black,
      );
      var response =
          await HttpManager.instance.doRequest("/api/changedir", parameters: {
        "name": oldFolderName,
        "rename": newFolderName,
        "frame_id": widget.frame?.frame_id ?? ""
      });
      if (!response.isSuccess) {
        EasyLoading.dismiss();
        EasyLoading.showToast(response.msg ?? "");
      }
      EasyLoading.dismiss();
      refreshIndicatorStateKey.currentState!.show();
    });
  }

  showEditFolderDialog(
      String title, String folderName, void Function(String) confirm) {
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return CustomCupertinoAlertDialog(
            title: Text(
              title,
              style: TextStyle(
                  fontSize: 16,
                  color: Color(0xff333333),
                  fontWeight: FontWeight.bold),
            ),
            content: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 8.5),
                  height: 44,
                  padding: EdgeInsets.symmetric(horizontal: 14),
                  decoration: BoxDecoration(
                      color: Color(0xffEAECEE),
                      borderRadius: BorderRadius.circular(10.0)),
                  child: TextField(
                    maxLines: 1,
                    minLines: 1,
                    cursorColor: Color(0xff3F74EF), // 设置光标颜色
                    decoration: InputDecoration(
                      hintMaxLines: 1,
                      border: InputBorder.none,
                      hintText:
                          appLocalForContext(context).pleaseEnterFolderName,
                      hintStyle: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    ),
                    onChanged: (value) {
                      folderName = value;
                    },
                  ),
                ),
                SizedBox(height: 10),
              ],
            ),
            actions: [
              CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  appLocalForContext(context).cancel,
                  style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff333333),
                      fontWeight: FontWeight.bold),
                ),
              ),
              CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  Navigator.pop(context);
                  confirm(folderName);
                },
                child: Text(
                  appLocalForContext(context).confirm,
                  style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff3F74EF),
                      fontWeight: FontWeight.bold),
                ),
              ),
            ],
          );
        });
  }

  triggleFolder(FrameFolderModel folder) {
    if (selectedFolder == null) {
      selectedFolder = folder;
    } else {
      if (selectedFolder?.id == folder.id) {
        selectedFolder = null;
      } else {
        selectedFolder = folder;
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: commonAppBar(appLocalForContext(context).chooseFrameFolder,
          actions: [buildRightNavbarItem()]),
      body: Container(
        color: Colors.white,
        height: double.infinity,
        width: double.infinity,
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: double.infinity,
                color: Color(0xffF2F2F2),
                padding: EdgeInsets.only(top: 8, left: 10, bottom: 8),
                child: Text(
                  style: TextStyle(fontSize: 13, color: Color(0xff666666)),
                  "${appLocalForContext(context).chooseFrameFolderPrefix}\"${widget.frame?.name ?? ""}\"${appLocalForContext(context).chooseFrameFolderSuffix}",
                  textAlign: TextAlign.left,
                ),
              ),
              Expanded(
                child: RefreshIndicator(
                  key: refreshIndicatorStateKey,
                  color: Color(0xff3F74EF),
                  onRefresh: () async {
                    return await fetchFolderList();
                  },
                  child: ListView.builder(
                    itemBuilder: (context, index) {
                      if (index == folderList.length) {
                        return buildAddFolderItem();
                      }
                      FrameFolderModel folder = folderList[index];
                      return folder.canEdit
                          ? buildSlideListItem(folder, selectedFolder)
                          : buildNormalListItem(folder, selectedFolder);
                    },
                    itemCount: folderList.length + 1,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  buildSlideListItem(
      FrameFolderModel folder, FrameFolderModel? selectedFolder) {
    return Slidable(
        // Specify a key if the Slidable is dismissible.
        key: ValueKey<String>(folder.id ?? ""),
        endActionPane: ActionPane(
          motion: ScrollMotion(),
          children: [
            CustomSlidableAction(
                onPressed: (context) {
                  renameFolder(context, folder.getName());
                },
                backgroundColor: Color(0xFF3f47ef),
                flex: 1,
                child: buildSlidActionItem(
                    appLocalForContext(context).folderRename)),
            CustomSlidableAction(
              onPressed: (context) {
                deleteFolder(context, folder);
              },
              backgroundColor: Color(0xFFFF6F6F),
              child:
                  buildSlidActionItem(appLocalForContext(context).folderDelete),
            ),
          ],
        ),

        // The child of the Slidable is what the user sees when the
        // component is not dragged.
        child: buildNormalListItem(folder, selectedFolder));
  }

  buildNormalListItem(
      FrameFolderModel folder, FrameFolderModel? selectedFolder) {
    return Container(
      color: Colors.white,
      child: ListTile(
        onTap: () {
          triggleFolder(folder);
        },
        title: Text(
          folder.getName(),
          style:
              TextStyle(fontWeight: FontWeight.bold, color: Color(0xff555555)),
        ),
        trailing: Image.asset(
            width: 22,
            height: 22,
            folder.id == selectedFolder?.id
                ? "images/icon_folder_selected.png"
                : "images/icon_folder_unselect.png"),
      ),
    );
  }

  buildSlidActionItem(String text) {
    return Text(
      style: TextStyle(fontSize: 11, color: Colors.white),
      text,
    );
  }

  buildAddFolderItem() {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.only(top: 10, bottom: 10, left: 15, right: 15),
        child: CupertinoButton(
          padding: EdgeInsets.zero,
          onPressed: () {
            addFolder(context);
          },
          child: Container(
            height: 50,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Color(0xfff5f5f5)),
            child: Center(
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.add, color: Color(0xff555555)),
                  SizedBox(width: 10),
                  Text(
                    appLocalForContext(context).createNewFrameFolder,
                    style: TextStyle(
                        fontWeight: FontWeight.w800, color: Color(0xff555555)),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  buildRightNavbarItem() {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        if (selectedFolder == null) {
          EasyLoading.showToast(
              appLocalForContext(context).atLeastChooseOneFolder);
          return;
        }
        AppAssetTransProvider.provider()
            .updateTransAssetBuffer("folder", selectedFolder);
        ARouter.instance.pagePush("/sendAssetPreview");
      },
      child: actionTextWidget(appLocal().next),
    );
  }
}
